#!/usr/bin/env bash

host_if="wlp3s0"
host_ip="172.22.28.163"

bridge_if=br0

modprobe tun
modprobe vhost
modprobe vhost_net

ip link add $bridge_if type bridge 2>/dev/null
ip link set $bridge_if up
ip addr add "10.255.0.1/8" dev $bridge_if

echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -F POSTROUTING
iptables -t nat -A POSTROUTING -s 10.0.0.0/8 -o $host_if -j SNAT --to-source $host_ip

ubuntu() {
qemu-system-x86_64 \
    -enable-kvm \
    -machine q35,accel=kvm -device intel-iommu \
    -cpu host -smp 4,sockets=4,cores=1,threads=1 \
    -m 8192 \
    -netdev tap,ifname=vmif,script=tap.sh,downscript=no,vhost=on,id=vmnic -device virtio-net-pci,netdev=vmnic \
    -drive file=/home/ubuntu_18_04_1.img,if=none,media=disk,id=vmdisk -device virtio-blk-pci,drive=vmdisk \
    -drive file=/home/ubuntu_18_04_1.iso,readonly=on,media=cdrom \
    -boot order=cd \
    -name vm \
    -vnc :9 \
    -daemonize
}

bsd() {
qemu-system-x86_64 \
    -enable-kvm \
    -machine q35,accel=kvm -device intel-iommu \
    -cpu host -smp 4,sockets=4,cores=1,threads=1 \
    -m 8192 \
    -netdev tap,ifname=vmif-bsd,script=tap.sh,downscript=no,vhost=on,id=vmnic-bsd -device virtio-net-pci,netdev=vmnic-bsd \
    -drive file=/home/bsd.img,if=none,media=disk,id=vmdisk-bsd -device virtio-blk-pci,drive=vmdisk-bsd \
    -boot order=cd \
    -name vm-bsd \
    -vnc :99 \
    -daemonize
}

if [[ 0 -eq $# ]]; then
# 默认启动 FreeBSD
    bsd
else
# 给定任意参数，则启动 Ubuntu
    ubuntu
fi
